package com.mfp.java.testYou.core;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.mfp.java.testYou.core.utils.Utils;

/**
 * Singleton for internationalization management.
 */
public class I18n {

	private static final Logger log = Logger.getLogger(I18n.class);

	private static final String I18N_MESSAGE_FILE_NAME = "messages_%s.properties"; 

	private static I18n instance;

	private Map<String, String> map;

	private I18n() {
		map = new HashMap<String, String>();
	}

	public static synchronized I18n getInstance() {
		if (instance == null) {
			instance = new I18n();
		}
		return instance;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException("Should not clone a singleton");
	}

	public String getMessage(String lang, String key) {
		String uId = lang + '.' + key;
		if (!map.containsKey(uId)) {
			String fileName = String.format(I18N_MESSAGE_FILE_NAME, lang);
			String value = Utils.readConfig(fileName, key);
			if (value == null) {
				log.warn("Can't find key for " + uId);
				return "???" + key;
			} else {
				map.put(uId, value);
			}
		}
		return map.get(uId);
	}
}
